import { http } from '../http';
import type { ApiResponse } from '~/api/types/http';
import type { UploadFileParams, UploadFileResponse } from '~/api/types/common';

/**
 * 通用API组合函数
 */
export const useCommonApi = () => {
  /**
   * 文件上传
   * @param params 上传参数
   * @returns 上传结果（注意：upload方法返回的是处理后的数据，不是useFetch对象）
   */
  const uploadFile = async (params: UploadFileParams) => {
    const formData = new FormData();
    formData.append('file', params.file);
    if (params.type) {
      formData.append('type', params.type);
    }
    if (params.folder) {
      formData.append('folder', params.folder);
    }

    const response = await http.upload<UploadFileResponse>(
      '/common/upload',
      formData
    );
    return response?.data;
  };

  /**
   * 获取系统配置
   * @returns useFetch 响应对象
   */
  const getSystemConfig = () => http.get('/common/config');

  /**
   * 获取字典数据
   * @param type 字典类型
   * @returns useFetch 响应对象
   */
  const getDictData = (type: string) => http.get(`/common/dict/${type}`);

  /**
   * 发送验证码
   * @param phone 手机号
   * @param type 验证码类型
   * @returns useFetch 响应对象
   */
  const sendSmsCode = (phone: string, type: 'login' | 'register' | 'reset') =>
    http.post('/common/sms/send', { phone, type });

  /**
   * 验证验证码
   * @param phone 手机号
   * @param code 验证码
   * @param type 验证码类型
   * @returns useFetch 响应对象
   */
  const verifySmsCode = (phone: string, code: string, type: string) =>
    http.post('/common/sms/verify', { phone, code, type });

  return {
    uploadFile,
    getSystemConfig,
    getDictData,
    sendSmsCode,
    verifySmsCode,
  };
};
